package org.springframework.samples.mvc.basic.business;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.samples.mvc.basic.model.Identifiable;

public class BusinessServiceMock<T extends Identifiable> implements BusinessService<T> {
	
	private Map<Object, T> objects = new ConcurrentHashMap<Object, T>();
	private static Long id = 1l;

	public void save(T object) {
		object.setId(id++);
		objects.put(object.getId(), object);
	}

	public T findById(Long id) {
		return objects.get(id);
	}

	public List<T> findAll() {
		return new ArrayList<T>(objects.values());
	}

	public void delete(Long id) {
		objects.remove(id);
	}

    @Override
    public List<T> findAll(int startIndex, int pageSize) {
        List<T> result = new ArrayList<T>();
        List<T> all = findAll();
        
        if (all.size() == 0) {
            System.out.println("No result found for start index: " + startIndex + " and page size: " + pageSize);
        	return result;
        }
        
        for (int i = startIndex; (i < startIndex + pageSize && i < all.size()); i++) {
             result.add(all.get(i));
        }
        System.out.println("Result for start index: " + startIndex + " and page size: " + pageSize + " : " + result);
        return result;
    }

    @Override
    public int count() {
        return objects.size();
    }

	@Override
	public List<T> findAll(int startIndex, int pageSize, T queryInfo) {
		throw new RuntimeException("Not yet implemented");
	}

	@Override
	public List<T> findAll(String orderBy) {
		throw new RuntimeException("Not yet implemented");
	}

}
